package com.magictower.primary.activity;

import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.ScrollView;
import android.widget.TextView;

import com.magictower.primary.R;
import com.magictower.primary.db.dao.AntivirusDao;
import com.magictower.primary.utils.MD5Utils;

import java.util.List;

/**
 * @author kejunzhan
 * @since 2017/12/21
 */

public class AntivirusActivity extends AppCompatActivity {
    // 扫描开始
    private static final int BEGING = 1;
    // 扫描中
    private static final int SCANING = 2;
    // 扫描结束
    private static final int FINISH = 3;

    private ImageView iv_scanning;
    private TextView tv_init_virus;
    private ProgressBar progressBar;
    private ScrollView scrollView;
    private LinearLayout ll_content;
    private Button bt_begin;

    private AntivirusDao dao;

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case BEGING:
                    tv_init_virus.setText("初始化八核引擎");
                    ll_content.removeAllViews();
                    break;
                case SCANING:
                    bt_begin.setText("停止扫描");
                    textView = new TextView(AntivirusActivity.this);
                    ScanInfo info = (ScanInfo) msg.obj;
                    if (info.desc) {
                        //病毒
                        textView.setText(info.appName + "有病毒");
                        textView.setTextColor(Color.RED);
                    } else {
                        //安全
                        textView.setText(info.appName + "扫描安全");
                        textView.setTextColor(Color.BLACK);
                    }
                    tv_init_virus.setText("正在扫描" + info.appName + ": "+ info.packageName);
                    ll_content.addView(textView);

                    //设置倒序
                    scrollView.post(new Runnable() {
                        @Override
                        public void run() {
                            //一直往下
                            scrollView.fullScroll(View.FOCUS_DOWN);
                        }
                    });
                    break;
                case FINISH:
                    // 当扫描结束的时候。停止动画
                    iv_scanning.clearAnimation();
                    tv_init_virus.setText("扫描结束。");
                    bt_begin.setText("重新扫描");
                    running = false;//设置停止
                    break;
            }
        }
    };
    private TextView textView;
    private RotateAnimation rotateAnimation;
    private boolean running = false;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_antivirus);
        iv_scanning = (ImageView) findViewById(R.id.iv_scanning);
        tv_init_virus = (TextView) findViewById(R.id.tv_init_virus);
        tv_init_virus.setSingleLine();
        bt_begin = (Button) findViewById(R.id.bt_begin);
        progressBar = (ProgressBar) findViewById(R.id.progressBar);
        scrollView = (ScrollView) findViewById(R.id.scrollView);
        ll_content = (LinearLayout) findViewById(R.id.ll_content);
        dao = new AntivirusDao();

        initUI();
    }

    private void initData() {
        new Thread() {
            @Override
            public void run() {
                Message msg = handler.obtainMessage();
                //Message msg = Message.obtain();//与上述一样
                msg.what = BEGING;
                handler.sendMessage(msg);
                SystemClock.sleep(1000);
                /*
                1.获取到所有安装的应用程序
                2.返回手机上面安装了多少个应用程序
                3.设置进度条的最大值
                 */
                PackageManager pm = getPackageManager();
                List<PackageInfo> installedPackages = pm.getInstalledPackages(0);
                int size = installedPackages.size();
                progressBar.setMax(size);
                ScanInfo scanInfo;

                int progress = 0;
                for (PackageInfo pkg : installedPackages) {
                    if (!running) {
                        msg = handler.obtainMessage();
                        msg.what = FINISH;
                        handler.sendMessage(msg);
                        return;
                    }
                    scanInfo = new ScanInfo();
                    scanInfo.appName = pkg.applicationInfo.loadLabel(pm).toString();
                    scanInfo.packageName = pkg.applicationInfo.packageName;
                    System.out.println(pkg.applicationInfo.packageName + "--" + pkg.packageName);
                    String sourceDir = pkg.applicationInfo.sourceDir;
                    String fileMD5 = MD5Utils.getFileMD5(sourceDir);
                    String virus = dao.checkFileVirus(fileMD5);
                    if (TextUtils.isEmpty(virus)) {
                        scanInfo.desc = false;//安全
                    } else {
                        scanInfo.desc = true;//病毒
                    }
                    progress ++;
                    //设置进度条
                    SystemClock.sleep(100);
                    //进度条可视为特殊进程，子线程中调用会加载至主线程中
                    progressBar.setProgress(progress);

                    msg = handler.obtainMessage();
                    msg.what = SCANING;
                    msg.obj = scanInfo;
                    handler.sendMessage(msg);
                }

                msg = handler.obtainMessage();
                msg.what = FINISH;
                handler.sendMessage(msg);
            }
        }.start();
    }

    private void initUI() {
        /**
         * 第一个参数表示开始的角度 第二个参数表示结束的角度 第三个参数表示参照自己 初始化旋转动画
         */
        rotateAnimation = new RotateAnimation(0, 360,
                Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        // 设置动画的时间
        rotateAnimation.setDuration(5000);
        // 设置动画无限循环
        rotateAnimation.setRepeatCount(Animation.INFINITE);
        // 设置动画停止在原处
        rotateAnimation.setFillAfter(true);
        //rotateAnimation.setFillBefore(false);
        rotateAnimation.setFillEnabled(true);
    }

    public void beginSearch(View view) {
        if (running) {
            running = false;
        } else {
            running = true;
            initData();
            // 开始动画
            iv_scanning.startAnimation(rotateAnimation);
        }
    }
    static class ScanInfo {
        boolean desc;
        String appName;
        String packageName;
    }
}
